package com.elinshaw.pattern.per;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.Socket;

/**
 * @author Administrator
 */
public class ClientHandler implements Runnable {

    private final Socket socket;

    private final String clientId;

    public ClientHandler(Socket socket) {
        this.socket = socket;
        this.clientId = socket.getInetAddress().getHostAddress() + ":" + socket.getPort();
    }

    @Override
    public void run() {

        try {
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            PrintStream printStream = new PrintStream(this.socket.getOutputStream());
            String s;
            while ((s = bufferedReader.readLine()) != null) {
                System.out.printf("client:%s--%s", clientId, s);
                if (s.equals("quit")) {
                    printStream.println("client will close");
                    printStream.flush();
                    socket.close();
                    break;
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

}
